module.exports = {
  // 获取站点详情
  async getDepotDetail(depotId) {
    const db = uniCloud.database()
    const dbCmd = db.command
    
    try {
      // 获取站点基本信息
      const depotRes = await db.collection('depot')
        .doc(depotId)
        .field({
          _id: true,
          name: true,
          location: true,
          address: true,
          contact: true,
          operating_hours: true,
          images: true,
          booking_policy: true,
          cancellation_policy: true,
          delivery_service: true,
          manager: true
        })
        .get()
      
      if (!depotRes.data || depotRes.data.length === 0) {
        return {
          code: 404,
          message: '站点不存在'
        }
      }
      
      const depot = depotRes.data[0]
      
      // 获取站点箱型信息
      const groupRes = await db.collection('locker_group')
        .where({
          depot_id: depotId,
          status: 1 // 启用的箱组
        })
        .field({
          _id: true,
          name: true,
          specs: true,
          total_cells: true
        })
        .get()
      
      // 计算可用格子数量
      const groupIds = groupRes.data.map(group => group._id)
      const cellRes = await db.collection('locker_cell')
        .where({
          group_id: dbCmd.in(groupIds),
          status: 0 // 空闲状态
        })
        .count()
      
      const availableCount = cellRes.total || 0
      
      // 获取站点评价
      const reviewRes = await db.collection('review')
        .where({
          depot_id: depotId
        })
        .orderBy('create_time', 'desc')
        .limit(5)
        .get()
      
      // 格式化数据
      const lockerTypes = groupRes.data.map(group => {
        return {
          id: group._id,
          name: this.getSizeName(group.specs.size_type),
          price: this.getPriceBySize(depotId, group.specs.size_type),
          desc: group.specs.suitcase_desc,
          icon: this.getIconBySize(group.specs.size_type),
          dimensions: group.specs.dimensions
        }
      })
      
      return {
        code: 0,
        message: '获取站点详情成功',
        data: {
          depot: {
            ...depot,
            availableCount,
            rating: this.calculateRating(reviewRes.data),
            reviews: reviewRes.data
          },
          lockerTypes
        }
      }
    } catch (e) {
      console.error('获取站点详情失败:', e)
      return {
        code: 500,
        message: '获取站点详情失败',
        data: null
      }
    }
  },
  
  // 根据尺寸类型获取名称
  getSizeName(sizeType) {
    const sizeMap = {
      0: '小箱型',
      1: '中箱型',
      2: '大箱型'
    }
    return sizeMap[sizeType] || '未知箱型'
  },
  
  // 根据尺寸类型获取图标
  getIconBySize(sizeType) {
    const iconMap = {
      0: '/static/small-locker.png',
      1: '/static/medium-locker.png',
      2: '/static/large-locker.png'
    }
    return iconMap[sizeType] || '/static/locker.png'
  },
  
  // 根据尺寸类型获取价格
  async getPriceBySize(depotId, sizeType) {
    const db = uniCloud.database()
    
    // 先查询站点特有价格
    const depotPriceRes = await db.collection('price_rule')
      .where({
        depot_id: depotId,
        cell_type: sizeType,
        is_default: false
      })
      .orderBy('effective_date', 'desc')
      .limit(1)
      .get()
    
    if (depotPriceRes.data && depotPriceRes.data.length > 0) {
      return depotPriceRes.data[0].price
    }
    
    // 查询默认价格
    const defaultPriceRes = await db.collection('price_rule')
      .where({
        cell_type: sizeType,
        is_default: true
      })
      .orderBy('effective_date', 'desc')
      .limit(1)
      .get()
    
    if (defaultPriceRes.data && defaultPriceRes.data.length > 0) {
      return defaultPriceRes.data[0].price
    }
    
    // 默认价格
    const defaultPrices = {0: 6, 1: 8, 2: 10}
    return defaultPrices[sizeType] || 8
  },
  
  // 计算平均评分
  calculateRating(reviews) {
    if (!reviews || reviews.length === 0) return 4.5
    const total = reviews.reduce((sum, review) => sum + review.rating, 0)
    return (total / reviews.length).toFixed(1)
  },
  
  // 获取可用格子
  async getAvailableCells(depotId, sizeType) {
    const db = uniCloud.database()
    const dbCmd = db.command
    
    try {
      // 获取对应尺寸的箱组
      const groupRes = await db.collection('locker_group')
        .where({
          depot_id: depotId,
          status: 1,
          'specs.size_type': sizeType
        })
        .field({
          _id: true
        })
        .get()
      
      if (!groupRes.data || groupRes.data.length === 0) {
        return {
          code: 404,
          message: '该站点没有此箱型'
        }
      }
      
      const groupIds = groupRes.data.map(group => group._id)
      
      // 获取可用格子
      const cellRes = await db.collection('locker_cell')
        .where({
          group_id: dbCmd.in(groupIds),
          status: 0 // 空闲状态
        })
        .field({
          _id: true,
          cell_code: true,
          qr_code: true
        })
        .get()
      
      return {
        code: 0,
        message: '获取可用格子成功',
        data: cellRes.data
      }
    } catch (e) {
      console.error('获取可用格子失败:', e)
      return {
        code: 500,
        message: '获取可用格子失败',
        data: null
      }
    }
  }
}